#!/usr/bin/python
#-*- coding: utf-8 -*-

# OsmOpenPhoto - Your photos displayed on an OpenStreetMap map.
# Copyright (C) 2012  Cédric Bonhomme - http://cedricbonhomme.org/
#
# For more information : https://bitbucket.org/cedricbonhomme/osmopenphoto/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

__author__ = "Cedric Bonhomme"
__version__ = "$Revision: 0.3 $"
__date__ = "$Date: 2012/07/13 $"
__revision__ = "$Date: 2012/07/23 $"
__copyright__ = "Copyright (c) Cedric Bonhomme"
__license__ = "GPLv3"

import cgi
import json

from openphoto import OpenPhoto

form = cgi.FieldStorage()
address = form.getvalue("address", "photos.cedricbonhomme.org")

html = '<html>\n' + \
        '<head>\n\t<title>Photos</title>\n' + \
        '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>\n' + \
        '<link rel="stylesheet" type="text/css" href="./style.css" />\n'

resp = None
try:
    client = OpenPhoto(host=address)
    resp = json.loads(client.get('/photos/list.json', {'pageSize':'1000'}))
except:
    html += '</head>\n'
    html += '<body>\n'
    html += '<p>Unable to contact the Web Service. Check the URL.</p>\n'
    html += '</body>\n'
    html += '</html>\n'


if resp != None:
    if resp["code"] != 200:
        html += '</head>\n'
        html += '<body>\n'
        html += '<p>There was a problem. The response from the Web Service is:<br />\n' + resp["message"] + '</p>\n'
        html += '</body>\n'
        html += '</html>\n'

    else:
        photos = resp["result"]
        geolocated_photos = [photo for photo in photos if photo["latitude"] != None]

        if len(geolocated_photos) == 0:
            html += '</head>\n'
            html += '<body>\n'
            html += '<p>There are no geolocalized photos for ' + address  +  '.</p>\n'
            html += '</body>\n'
            html += '</html>\n'

        else:

            html += '<script src="http://openlayers.org/api/OpenLayers.js"></script>\n' + \
                    '<script src="./scripts.js"></script>\n'
            html += """<script>
                    var photos_location;
                    function init(position) {
                        var size = new OpenLayers.Size(21,25);
                        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
                        var popupClass, popupContentHTML;
                        var zoom=10;
                        AutoSizeAnchoredMinSize = OpenLayers.Class(OpenLayers.Popup.Anchored, {
                        'autoSize': true,
                        'minSize': new OpenLayers.Size(10,10)
                        });
                        map = new OpenLayers.Map("mapdiv" , {
                            controls:[
                                new OpenLayers.Control.Navigation(),
                                new OpenLayers.Control.PanZoomBar(),
                                new OpenLayers.Control.LayerSwitcher(),
                                new OpenLayers.Control.Attribution()]});
                        photos_location = new OpenLayers.Layer.Markers("Photos");
                        map.addLayer(photos_location);
                        map.addLayer(new OpenLayers.Layer.OSM());
                        var lonLatCenter = new OpenLayers.LonLat(position.coords.longitude, position.coords.latitude).transform(
                        new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject() )
                        map.setCenter (lonLatCenter, zoom);\n"""

            for idx, photo in enumerate(geolocated_photos):
                try:
                    float(photo["longitude"])
                except:
                    continue
                html += """
                        var photo%s = new OpenLayers.LonLat(%s, %s).transform(
                            new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
                            popupClass = AutoSizeAnchoredMinSize;""" % \
                                (idx, photo["longitude"], photo["latitude"])
                        
                html += """
                            popupContentHTML = '<a href="%s"><img src="%s" witdth="50%%" height="50%%" /></a><br />Date: %s-%s-%s<br />License: %s';""" % \
                                (photo["url"], photo["pathBase"], photo["dateTakenYear"], photo["dateTakenMonth"], photo["dateTakenDay"], \
                                photo["license"])

                html += """
                            addMarker(photo%s, popupClass, popupContentHTML, true);""" % \
                                (idx,)

            html += "}\n</script>\n</head>\n"
            html += '<body onload="getLocation();">\n'
            html += """<h1>Geolocated photos for <a href="http://%s">%s</a></h1>\n""" % (address, address)
            html += '<div id="mapdiv" style="width:100%;height:100%;"></div>\n'
            html += "<br />\n"
            html += "</body>\n</html>"


# Finally print the web page.
print "Content-type:text/html\r\n\r\n"
print html